package com.core.cloudcommon;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * @author =====Lqj=====
 * @className CommonGlobalExceptionHandler
 * @description 全局异常定义
 * @create 2024/11/17 20:17
 **/

@Slf4j
@ControllerAdvice
public class CommonGlobalExceptionHandler {

    /**
     * 处理自定义业务异常
     */
    @ExceptionHandler(CommonCustomException.class)
    public ResponseEntity<Object> handleCommonCustomException(CommonCustomException ex) {
        log.warn("业务异常: code={}, message={}, requuid={}", ex.getCode(), ex.getMessage(), ex.getRequuid());

        // 构造返回的错误结构，使用CommonResult格式
        CommonResult<Object> result = CommonResult.error(ex.getCode(), ex.getMessage());
        result.setRequuid(ex.getRequuid());
        result.setTimestamp(ex.getTimestamp());

        // 根据错误码决定HTTP状态码
        HttpStatus httpStatus = getHttpStatusByErrorCode(ex.getCode());

        return new ResponseEntity<>(result, httpStatus);
    }

    /**
     * 处理参数验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Object> handleValidationException(MethodArgumentNotValidException ex) {
        log.warn("参数验证异常: {}", ex.getMessage());

        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });

        CommonResult<Object> result = CommonResult.error(400, "参数验证失败", errors);
        return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理绑定异常
     */
    @ExceptionHandler(BindException.class)
    public ResponseEntity<Object> handleBindException(BindException ex) {
        log.warn("参数绑定异常: {}", ex.getMessage());

        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });

        CommonResult<Object> result = CommonResult.error(400, "参数绑定失败", errors);
        return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理其他未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> handleGenericException(Exception ex) {
        log.error("系统异常: ", ex);

        CommonResult<Object> result = CommonResult.error(500, "系统内部错误，请联系管理员");
        return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * 根据错误码决定HTTP状态码
     */
    private HttpStatus getHttpStatusByErrorCode(Integer errorCode) {
        if (errorCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }

        // 根据错误码范围决定HTTP状态码
        if (errorCode >= 200000 && errorCode < 300000) {
            // 业务错误，返回200但在body中包含错误信息
            return HttpStatus.OK;
        } else if (errorCode >= 400000 && errorCode < 500000) {
            // 客户端错误
            return HttpStatus.BAD_REQUEST;
        } else if (errorCode >= 500000) {
            // 服务器错误
            return HttpStatus.INTERNAL_SERVER_ERROR;
        } else {
            // 其他错误，返回200让前端处理
            return HttpStatus.OK;
        }
    }
}
